﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

using Alicanto.Helpers;
using Alicanto.Api;

namespace Alicanto.Compilation.Code.Operators.Sequence
{
    internal class OpEnumerable : ICodeGenerator
    {
        public Expression Code { get; private set; }

        public IEnumerable<ParseInstruction> Generate(TokenSequence tokens, Scope scope)
        {
            GetEvaluation evaluation = new GetEvaluation();
            yield return evaluation;

            ParseExpression remainder = new ParseExpression();
            yield return remainder;

            Expression x = evaluation.Expression;
            Expression y = remainder.Expression;

            if (Typing.IsNumber(evaluation.Expression.Type) && Typing.IsNumber(remainder.Expression.Type))
            {
                x = Conversion.Ensure(x, typeof(int));
                y = Conversion.Ensure(x, typeof(int));

                this.Code = Expression.New(
                    typeof(IntIter).GetConstructor(new Type[] { typeof(int), typeof(int) }),
                    x,
                    y
                );
            }
        }
    }
}
